package beans;


import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

/**
 * 使用 BeanInfo 实现 bean 实体与 map 之间的相互转换
 * @author xiaoming
 * @date 2021-03-20 10:27
 */
public class BeanInfoTransformTest {
    public static void main(String[] args) throws IllegalAccessException, IntrospectionException, InvocationTargetException {
        User user = new User("xiaoming", 18);

        Map<String, Object> userMap = beanTransformToMap(user);

        System.out.println(userMap);

    }
    /**实体转map
     * @param user
     * @return
     * @throws IllegalAccessException
     * @throws IllegalArgumentException
     * @throws InvocationTargetException
     * @throws IntrospectionException
     */
    private static Map<String, Object> beanTransformToMap(User user)
            throws IllegalAccessException, IllegalArgumentException, InvocationTargetException, IntrospectionException, IntrospectionException {

        Map<String, Object> map = new HashMap<String, Object>();

        BeanInfo beanInfo = Introspector.getBeanInfo(user.getClass());
        PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();

        for (PropertyDescriptor property : propertyDescriptors) {
            String key = property.getName();
            // 过滤class属性
            if (key.equals("class")) {
                continue;
            }
            // 得到property对应的getter方法
            Method getter = property.getReadMethod();
            Object value = getter.invoke(user);
            map.put(key, value);
        }
        return map;
    }

}


class User {
    /**
     * 姓名
     */
    private String name;
    /**
     * 年龄
     */
    private int age;


    public User() {
    }

    public User(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
}
